package me.chan.chatting.server.config;

import io.netty.util.internal.StringUtil;
import me.chan.chatting.server.serialize.SerializeAlgo;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputFilter;
import java.util.Objects;
import java.util.Properties;

public class ApplicationConfig {

    private static Properties properties;

    private static String serializer;

    static {

        // system argument has the highest priority
        serializer = System.getProperty("project.serializer");
        if (Objects.isNull(serializer)) {
            try (InputStream in = ApplicationConfig.class.getClassLoader().getResourceAsStream("application.properties")) {
                properties = new Properties();
                properties.load(in);


                // read the configuration argument from application.properties file
                serializer = properties.getProperty("netty.codec.serialize");
                if (StringUtil.isNullOrEmpty(serializer)) {
                    serializer = SerializeAlgo.JDK.name();
                }
            } catch (IOException e) {
                throw new ExceptionInInitializerError(e);
            }
        } else {
            serializer = System.getProperty("project.serializer");
        }
    }

    public static SerializeAlgo getSerializeAlgo() {
        SerializeAlgo algo = SerializeAlgo.valueOf(serializer);
        if (Objects.isNull(algo)) {
            // default
            return SerializeAlgo.JDK;
        }

        return algo;
    }

}